from django.db import models
from django.contrib.auth.models import User



class UserProfileManager(models.Manager):
    def is_privileged(self, user):
        try:
            up = self.get(user=user)
        except UserProfile.DoesNotExist:
            return False
        return up.permission == u'M' or up.permission == u'A'#MODERATOR_PERM or self.get(user=user).permission == ADMIN_PERM

    def get_profile(self, user):
        return self.get(user=user)

class UserProfile(models.Model):
 #   TIMEZONE_CHOICES = tuple([(tz, tz) for tz in common_timezones])

    USER_PERM = u'U'
    MODERATOR_PERM = u'M'
    ADMIN_PERM = u'A'

    PER_PAGE_CHOICES = (
        (10, u'10'),
        (20, u'20'),
        (30, u'30'),
        (40, u'40'),
    )

    
    PERM_CHOICES = (
        (USER_PERM, u'User'),
        (MODERATOR_PERM, u'Moderator'),
        (ADMIN_PERM, u'Admin'),
    )
    
    user = models.ForeignKey(User, unique=True)
    location = models.CharField(max_length=100, blank=True, default='unknown')
    website  = models.URLField(max_length=200, verify_exists=False, blank=True)
    picture = models.ImageField(upload_to = 'profile_photos/%Y/%m/%d',default='profile_photos/no_user_photo.jpg')
    signature = models.TextField(default="")
    permission = models.CharField(choices=PERM_CHOICES,max_length=1,default=USER_PERM)
    pagination_preference = models.IntegerField(choices=PER_PAGE_CHOICES,default=20)
    
    objects = UserProfileManager()
    
    def save(self):
        if not self.pk:
            self.user.groups.add()
        super(UserProfile,self).save()
    
    def __unicode__(self):
        return unicode(self.user)
    
    class Admin:
        pass
    
    class Meta:
        verbose_name = "User Profile"
        verbose_name_plural = "User Profiles"
